---
category: String
created: '2020-04-19'
title: Replace all line breaks with br elements
updated: '2021-10-13'
---

**JavaScript version**

```js nl2br.js
const nl2br = (str) => str.replace(new RegExp('\r?\n', 'g'), '<br>');

// In React
str.split('\n').map((item, index) => (
    <React.Fragment key={index}>
        {item}
        <br />
    </React.Fragment>
));
```

**TypeScript version**

```ts nl2br.ts
const nl2br = (str: string): string => str.replace(new RegExp('\r?\n', 'g'), '<br>');
```
